package menu

import (
	"easy-sys/base/dao"
	"easy-sys/base/entity"

	"github.com/jinzhu/gorm"
)

func List(sysMenu SysMenu, page entity.EasyPage) entity.EasyPage {
	var menus []SysMenu
	dao.Db.Where(sysMenu).Limit(page.PageSize()).Offset(page.PageOffset()).Find(&menus)
	page.Records = menus
	var total int
	dao.Db.Model(&SysMenu{}).Where(sysMenu).Count(&total)
	page.Total = total
	return page
}

func Save(sysMenu SysMenu) int64 {
	var db *gorm.DB
	if sysMenu.MenuId == 0 {
		db = dao.Db.Create(&sysMenu)
	} else {
		db = dao.Db.Model(&sysMenu).Where("menu_id = ?", sysMenu.MenuId).Update(&sysMenu)
	}
	return db.RowsAffected
}

func GetRoleMenuByRoleId(roleId uint64) []SysMenu {
	var menus []SysMenu
	dao.Db.Where(`sys_menu.menu_id IN ( SELECT menu_id FROM sys_role_menu rm
		WHERE
			rm.role_id = ?
		)
		`, roleId).Order("menu_order", true).Find(&menus)
	return menus
}

func All() []SysMenu {
	var menus []SysMenu
	dao.Db.Find(&menus)
	return getMenuChildByParentId(menus, 0)
}

func getMenuChildByParentId(menuArr []SysMenu, parentId uint64) []SysMenu {
	var childList []SysMenu
	for i := 0; i < len(menuArr); i++ {
		var sysMenu = menuArr[i]
		if sysMenu.MenuParentId == parentId {
			sysMenu.Children = getMenuChildByParentId(menuArr, sysMenu.MenuId)
			childList = append(childList, sysMenu)
		}
	}
	return childList
}

func Delete(sysMenu SysMenu) int64 {
	var db *gorm.DB
	if sysMenu.MenuId != 0 {
		db = dao.Db.Where("menu_id = ?", sysMenu.MenuId).Delete(&sysMenu)
	}
	return db.RowsAffected
}

// GetMenuNoAuth 获取不需要权限的菜单
func GetMenuNoAuth() []SysMenu {
	var menus []SysMenu
	dao.Db.Where(`menu_auth is null or menu_auth = ''`).Order("menu_order", true).Find(&menus)
	menus = getMenuChildByParentId(menus, 0)
	return menus
}

// GetUserPermission 获取用户权限点
func GetUserPermission(userId uint64) []string {
	var permissions []string

	dao.Db.Model(&SysMenu{}).Where(`sys_menu.menu_id IN (
		SELECT
			menu_id
		FROM
			sys_role_menu rm
		WHERE
			rm.role_id IN (
				SELECT
					role_id
				FROM
					sys_user_role ur
				WHERE
					ur.user_id = ?
			)
			and menu_auth is not null and menu_auth != ""
	)`, userId).Pluck("menu_auth", &permissions)
	return permissions
}

func GetUserMenu(userId uint64) []SysMenu {
	var menus []SysMenu
	dao.Db.Where(`sys_menu.menu_id IN (
		SELECT
			menu_id
		FROM
			sys_role_menu rm
		WHERE
			rm.role_id IN (
				SELECT
					role_id
				FROM
					sys_user_role ur
				WHERE
					ur.user_id = ?
			)
		union all 
	SELECT
			menu_id
		FROM
			sys_menu rm1
		WHERE
			rm1.menu_auth is null or rm1.menu_auth = ''
			
	)`, userId).Order("menu_order", true).Find(&menus)
	menus = getMenuChildByParentId(menus, 0)
	return menus
}
